#include<stdio.h>
#include<stdlib.h>
#include "seqlist.h"

typedef struct _tag_SeqList
{
    void ** node;
    int length;
    int size;
}TSeqList;


SeqList *SeqList_New(int size)
{
    if(size <= 0)
    {
        printf("SeqList_new:size <= 0 \n");
        return NULL;
    }
    TSeqList *list = (TSeqList*)malloc(sizeof(TSeqList));
    if(list == NULL)
    {
        printf("SeqList_new:list==NULL\n");
        return NULL;
    }
    list->length = 0;
    list->size  = size;
    list->node = (void**)malloc(sizeof(void*) * size);
    return list;
}

void SeqList_Delete(SeqList *list)
{
    if(list ==NULL)
    {
        printf("SeqList_Delete:list==NULL\n");
        return ;
    }
    TSeqList *tlist = (TSeqList*)list;
    free(tlist->node);
    free(tlist);
    return ;
}

void SeqList_Clear(SeqList*list)
{
    if(list == NULL)
    {
        printf("SeqList_Clear:list ==NULL\n");
        return;
    }
    TSeqList *tlist = (TSeqList*)list;
    tlist->length = 0;
    return;
}

int SeqList_Length(SeqList*list)
{
    if(list == NULL)
    {
        printf("SeqList_Length:list ==NULL\n");
        return -1;
    }
    TSeqList *tlist = (TSeqList*)list;
    
    return tlist->length;
}

int SeqList_Size(SeqList*list)
{
    if(list == NULL)
    {
        printf("SeqList_Length:list ==NULL\n");
        return -1;
    }
    TSeqList *tlist = (TSeqList*)list;
    return tlist->size;
}

int SeqList_Insert(SeqList*list,SeqListNode* node,int pos)
{
    if(list == NULL|| node == NULL)
    {
        printf("SeqList_Insert:list == NULL\n");
        return -1;
    }
    if(pos<0)
    {
        printf("SeqList_Insert: pos<0\n");
        return -1;
    }
    TSeqList *tlist = (TSeqList*)list;
    if(tlist->length > tlist->size)
    {
        printf("SeqList_Insert: list is full");
        return -1;
    }
    if(pos>=tlist->length)
    {
        pos = tlist->length;
    }
    for(int i = tlist->length; i > pos; --i)
    {
        tlist->node[i]=tlist->node[i-1];
    }
    tlist->node[pos] = node;
    tlist->length++;
    return pos;
}

SeqListNode *SeqList_Get(SeqList*list,int pos)
{
    if(list == NULL || pos < 0)
    {
        printf("SeqList_Get: list ==NULL || pos < 0\n");
        return NULL;
    }
    TSeqList *tlist = (TSeqList *)list;
    if(pos >= tlist->length)
    {
        printf("SeqList_Get:pos > length\n");
        return NULL;
    }
    
    return tlist->node[pos];
}

SeqListNode *SeqList_Erase(SeqList*list,int pos)
{
    if(list == NULL || pos <0)
    {
        printf("SeqList_Erase:list == NULL || pos <0\n");
        return NULL;
    }
    TSeqList *tlist = (TSeqList *)list;
    SeqListNode * ret = NULL;
    if(pos >= tlist->length)
    {
        printf("SeqList_Erase:pos > length\n");
        return NULL;
    }

    ret = tlist->node[pos];
    for(int i = pos+1; i< (tlist->length); ++i)
    {
        tlist->node[i-1] = tlist->node[i];
    }
    tlist->length--;
    return ret;
}
